<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索与添加区域 -->

      <el-row :gutter="20">
        <el-col :span="8"
          ><el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getUserList"
          >
            >
            <el-button
              @click="getUserList"
              slot="append"
              icon="el-icon-search"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserdialogVisible"
            >添加用户</el-button
          ></el-col
        >
      </el-row>

      <!-- 用户列表区域 -->
      <template>
        <el-table :data="userlist" border stripe>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column label="状态">
            <template v-slot="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChanged(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUser(scope.row.id)"
              ></el-button>
              <!-- 分配按钮 -->

              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                ></el-button>
              </el-tooltip>
              <!-- 删除角色按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 页码区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区 -->
      <span
        ><el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="70px"
          ><el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 底部按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的操作 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editguanbi"
      width="50%"
      @close="editClosed"
    >
      <span
        ><el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
          ><el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item> </el-form
      ></span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editguanbi = false">取 消</el-button>
        <el-button type="primary" @click="editUserDialogVisible"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //自定义校验规则, 验证邮箱规则
    // 规则，待校验值，回调函数
    var checkEmail = (rule, value, cb) => {
      //验证邮箱的正则表达式
      const regEmail =
        /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
      //如果这个值返回值是true，验证通过
      // test() 方法用于检测一个输入的value是否匹配,返回布尔值
      if (regEmail.test(value)) {
        //合法邮箱
        return cb();
      }
      //非法，请输入合法邮箱
      cb(new Error("请输入合法的邮箱"));
    };
    //校验手机号规则
    var checkMobile = (rule, value, cb) => {
      const regMobile =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      //定义用户列表的参数对象，这样就不用在请求体里面直接写了
      queryInfo: {
        //搜索关键字
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      userinfo: "",
      //默认隐藏对话框
      addDialogVisible: false,
      //修改用户对话框的显示与隐藏
      editguanbi: false,
      //添加用户的表单数据对象
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //修改表单数据对象
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      //添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 16, message: "长度在 3 到 16个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //编辑表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //发起当前组件的数据请求
    this.getUserList();
  },
  methods: {
    //定义函数
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    //这一页展示几行
    handleSizeChange(newSize) {
      //把监听到的newSize保存到data身上
      this.queryInfo.pagesize = newSize;
      //既然赋值了，重新获取数据
      this.getUserList();
    },
    //当前的页码值如果发生了变化,接收一个最新的页码值，将他保存好
    handleCurrentChange(newPage) {
      //当前显示的是第几页，把最新值得到
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    //监听状态改变
    async userStateChanged(userinfo) {
      // console.log(userinfo);拿到了这个值就应该调用api接口来保存这个状态。
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        //既然更新失败，就要把修改改回去
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新页面状态成功！");
    },
    //点击弹出添加用户对话框
    addUserdialogVisible() {
      this.addDialogVisible = true;
    },
    //添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败!");
        }
        this.$message.success("添加用户成功");
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    //监听添加用户表单关闭事件
    addDialogClosed() {
      // console.log(this);
      this.$refs.addFormRef.resetFields();
    },
    // 修改用户确定按钮事件
    editUserDialogVisible() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        //editForm就是我们查询到的数据对象，同时只要我们对数据进行了修改也会同步到editForm中，所以可以直接从eidtForm身上取。并提交修改后的两个信息参数，
        const { data: res } = await this.$http.put(
          `users/` + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新用户失败!");
        }

        this.editguanbi = false;
        this.getUserList();
        this.$message.success("更新用户成功");
      });
    },
    //修改按钮事件,
    async editUser(id) {
      //这里要注意因为id是传过来的动态数据，不能直接/id,因为是携带在url中的，所以不用params
      const { data: res } = await this.$http.get(`users/` + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败!");
      }

      this.editForm = res.data;
      this.editguanbi = true;
    },
    // 修改表单关闭之后的重置
    editClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 根据id删除对应的用户数据
    async removeUserById(id) {
      //弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //如果文本确认删除，这返回值为字符串confirm
      // 如果用户取消了删除，这返回值为字符串cancel,不要去质疑这个结果，这是老子是log打印出来的。
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        //type 取值 ‘success’(成功) /warning(警告)/info(消息)/error(错误)/
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("删除用户成功");
      this.getUserList();
    },
  },
};
</script>
<style lang="less" scoped>
</style>